import Vue from 'vue'
import Router from 'vue-router'
// import { getUserInfo } from '@/api/user'
import Layout from '@/layout'

Vue.use(Router)

// 定义路由表
export const constantRoutes = [
  // ...
  { path: '*', redirect: '/404', hidden: true }
]

const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: constantRoutes
})

// 根据菜单权限动态生成路由
function generateRoutes (menuList) {
  const routes = []
  menuList.forEach(menu => {
    const route = {
      path: menu.path,
      component: menu.children ? Layout : resolve => require([`@/views${menu.path}.vue`], resolve),
      name: menu.name,
      meta: menu.meta || {},
      children: menu.children ? generateRoutes(menu.children) : []
    }
    routes.push(route)
  })
  return routes
}

router.beforeEach(async (to, from, next) => {
  if (to.path === '/login') {
    next()
    return
  }

  const userInfo = await getUserInfo()

  // 如果用户信息中包含菜单权限列表，就根据菜单权限动态生成路由
  if (userInfo && userInfo.menuList) {
    const accessedRoutes = generateRoutes(userInfo.menuList)
    router.options.routes = constantRoutes.concat(accessedRoutes)
    router.addRoutes(accessedRoutes)
    next({ ...to, replace: true })
  } else {
    next('/login')
  }
})

export default router